package com.highper.common.interceptor;

import cn.dev33.satoken.context.SaHolder;
import cn.dev33.satoken.id.SaIdUtil;
import com.highper.common.constant.ExceptionMessageConstant;
import com.highper.common.constant.ResponseCodeConstant;
import com.highper.common.entity.response.HighperResponse;
import com.highper.common.sehcma.ContextHandler;
import com.highper.common.util.ServletUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.lang.NonNull;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Author ZhangGJ
 * @Date 2022/01/27 15:56
 */
@Slf4j
public class ServerProtectInterceptor implements HandlerInterceptor {

    private final String serviceName;

    public ServerProtectInterceptor(String serviceName) {
        this.serviceName = serviceName;
    }

    @Override
    public boolean preHandle(@NonNull HttpServletRequest request, @NonNull HttpServletResponse response, @NonNull Object handler) throws Exception {
        String token = SaHolder.getRequest().getHeader(SaIdUtil.ID_TOKEN);
        try {
            SaIdUtil.checkToken(token);
            ContextHandler.setSchema(ServiceSchema.schema(serviceName));
        } catch (Exception e) {
            e.printStackTrace();
            log.error(ExceptionMessageConstant.GATEWAY_ERROR);
            ServletUtil.makeResponse(response, MediaType.APPLICATION_JSON_VALUE,
                    HttpServletResponse.SC_FORBIDDEN,
                    HighperResponse.failure(ResponseCodeConstant.GATEWAY_ERROR,
                            ExceptionMessageConstant.GATEWAY_ERROR));
            return false;
        }
        return HandlerInterceptor.super.preHandle(request, response, handler);
    }

    @Override
    public void afterCompletion(@NonNull HttpServletRequest request, @NonNull HttpServletResponse response, @NonNull Object handler, Exception ex) throws Exception {
        ContextHandler.remove();
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }

}
